package com.superbit.service.user.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import com.superbit.core.entry.UserActivityInfo;
import com.superbit.core.entry.UserBaseInfo;
import com.superbit.core.entry.UserLoginLog;
import com.superbit.core.entry.UserSafeInfo;
import com.superbit.core.exception.BusinessException;
import com.superbit.core.exception.ParamInvalidException;
import com.superbit.core.service.LoginService;
import com.superbit.core.service.RegisterService;
import com.superbit.service.user.daodefine.AppConfigDao;
import com.superbit.service.user.daodefine.UserActivityInfoDao;
import com.superbit.service.user.daodefine.UserBaseInfoDao;
import com.superbit.service.user.daodefine.UserLoginLogDao;
import com.superbit.service.user.daodefine.UserRedisDao;
import com.superbit.service.user.daodefine.UserSafeInfoDao;
import com.superbit.service.util.CommonUtils;
import com.superbit.service.util.GoogleAuthUtils;
import com.superbit.service.util.StringTools;
import com.superbit.utils.constantutil.CollectionUtils;
import com.superbit.utils.dbutil.RedisKeyUtils;
import com.superbit.utils.mailutil.EmailFailException;
import com.superbit.utils.mailutil.EmailSendService;
import com.superbit.utils.mobileutil.MobileMessService;

/** @author  WangZhenwei 
  * @date 创建时间：2018年1月12日 下午2:53:26  
  * @descrip 用户登录业务的实现类
  */
@Service
public class LoginServiceImpl implements LoginService{

	@Autowired
	private UserRedisDao userRedisDao;
	
	@Autowired
	private UserBaseInfoDao userBaseInfoDao;
	
	@Autowired
	private UserSafeInfoDao userSafeInfoDao;
	
	@Autowired
	private UserActivityInfoDao userActivityInfoDao;
		
	@Autowired
	private AppConfigDao appConfigDao;
	
	@Autowired
	private UserLoginLogDao loginLogDao;
	
	@Autowired
	private MobileMessService mobileMessService;
	
	@Autowired
	private EmailSendService emailSendService;
	
	@Autowired
	private RegisterService registerService;
	
	private int loginFailLimit;
	
	private int phoneSendLimit;
	
	private int phoneMessageVerifyLimit;
	
	private int phoneMessageSendLimit;
	
	private int emailMessageVerifyLimit;
	
	private int emailMessageSendLimit;
	
//	@Value("${ctx}")
	private String ctx;
	
	@PostConstruct
	private void init(){
		appConfigDao.getAppConfigIntValue("loginFailLimit", 5);
		phoneSendLimit = appConfigDao.getAppConfigIntValue("phoneSendLimit", 5);
		phoneMessageSendLimit = appConfigDao.getAppConfigIntValue("phoneMessageSendLimit", 5);
		phoneMessageVerifyLimit = appConfigDao.getAppConfigIntValue("phoneMessageVerifyLimit", 5);
		emailMessageSendLimit = appConfigDao.getAppConfigIntValue("emailMessageSendLimit", 5);
		emailMessageVerifyLimit = appConfigDao.getAppConfigIntValue("emailMessageVerifyLimit", 5);
	}
	
	/**
	 * 处理用户登录的方法
	 * @throws BusinessException 
	 * 
	 */
	@Override
	public Map<String, Object> login(String account, byte accountType, String password, Map<String, Object> accessData) throws BusinessException {
		// 创建用户登录对象
		UserLoginLog userLoginLog = new UserLoginLog();
		userLoginLog.setRemoteIP(accessData.get("remoteIP")+"");
		userLoginLog.setLoginMode((Byte)accessData.get("loginMode"));
		userLoginLog.setLoginDate(System.currentTimeMillis());
		
		// 根据账号、账号类型获取用户的基本信息
		UserBaseInfo userBaseInfo = userBaseInfoDao.getUserBaseInfoByAccount(account, accountType);
		if(null == userBaseInfo){
			// 如果用户账号正确就产生登录日志
			userLoginLog.setLoginStatus((byte)1);   // 登录结果：0成功，1失败
			userLoginLog.setErrorCode((byte)1);     // 用户登录错误码：0通过 1用户不存在或密码错误 2用户被锁定
			loginLogDao.saveLoginLog(userLoginLog);
			throw new BusinessException("US573", "The user is not exist!", null);
		}
		
		int userId = userBaseInfo.getUserId();
		userLoginLog.setUserId(userId);
		userLoginLog.setUserId(userId);
		// 判断用户是否被锁定，返回用户安全信息对象
		UserSafeInfo userSafeInfo = userSafeInfoDao.userIsLocked(userId);
		if(userSafeInfo.getLockStatus() != 0){
			// 记录登录失败的日志
			userLoginLog.setLoginStatus((byte)1);
			userLoginLog.setErrorCode((byte)2);
			throw new BusinessException("US752", "The user is locked!", null);
		}
		
		// 此时账户校验完毕，开始校验密码
		String userPassword = userBaseInfo.getPassword();
		String validPassword = CommonUtils.EncoderByMd5(password);
		// 判断密码是否匹配
		if(! userPassword.equals(validPassword)){
			// 增加密码输入错误次数
			int count = (int) userRedisDao.addPasswordErrorTimes(userBaseInfo.getUserId());
			// 允许密码输入错误次数
			if(count >= loginFailLimit){
				// 删除密码错误次数统计
				userRedisDao.dropPasswordErrorTimesCount(userId);
				// 设置锁定截止时间，账户锁定2小时
				long lockDeadline = System.currentTimeMillis() + RedisKeyUtils.lockUserTime();
				userSafeInfoDao.lockUser(userId, lockDeadline);
				// 记录登陆失败日志
				userLoginLog.setLoginStatus((byte)1);
				userLoginLog.setErrorCode((byte)2);
				loginLogDao.saveLoginLog(userLoginLog);
				throw new BusinessException("US752", "The user is locked!", null);
			}else{
				// 密码输入错误但还没有错到5次 记录登录失败日志
				userLoginLog.setLoginStatus((byte)1);
				userLoginLog.setErrorCode((byte)1);
				loginLogDao.saveLoginLog(userLoginLog);
				throw new BusinessException("US752", "The user is locked!", null);
			}
		}
		
		// 此时账户和密码均验证通过
		userRedisDao.dropPasswordErrorTimesCount(userId);
		// 记录日志
		userLoginLog.setLoginStatus((byte)0);
		userLoginLog.setErrorCode((byte)0);
		loginLogDao.saveLoginLog(userLoginLog);	
		
		Map<String, Object> map = new HashMap<String, Object>();
		//int loginAuthentication = userSafeInfo.getLoginAuthentication();
		map.put("userId", userId);
		map.put("bindPhone", userSafeInfo.getBindPhone());
		map.put("googlePrivateKey", userSafeInfo.getGooglePrivateKey());
		//map.put("loginAuthentication", loginAuthentication);
		// chooseLoginAuthentication:验证方式（0 没有 1 手机 2谷歌）
		//map.put("chooseLoginAuthentication", this.chooseLoginAuthentication(userId));
		return map;
	}

	
	/**
	 * 忘记密码验证账号的业务方法
	 * @throws BusinessException 
	 * @throws EmailFailException 
	 */
	@SuppressWarnings("null")
	@Override
	public UserBaseInfo forgetLoginPassword(String account) throws BusinessException, EmailFailException {
		UserBaseInfo userBaseInfo = userBaseInfoDao.getUserBaseInfoByAccount(account);
		// 根据账户查询用户基本信息
		if(null == userBaseInfo){
			throw new BusinessException("US753", "The user is not exist!", null);
		}
		
		// 【如果账户是手机的情况】
		if(userBaseInfo.getAccountType()==2 && userBaseInfo.getPhone()!=null){
			Map<String, String> tempInfo = userRedisDao.getPhoneResetTempInfo(userBaseInfo.getPhone());
			    // 手机发送次数限制为5次
			if(null == tempInfo || tempInfo.isEmpty() || Integer.parseInt(tempInfo.get("phoneMessageSendCount")+"")< phoneMessageSendLimit){
				int phoneMessageSendCount = 0;
				// 手机注册的临时信息存在
				if(null != tempInfo && !tempInfo.isEmpty()){
					phoneMessageSendCount  = Integer.parseInt(tempInfo.get("phoneMessageSendCount")+"");
				}else{
					tempInfo  = new HashMap<String,String>();
				}
				
				// 生成六位随机数的验证码
				String captcha = CommonUtils.randCode("", 6);
				String phone = userBaseInfo.getPhone();
				// 用户忘记登录密码时发送手机验证码
				//registerService.sendMessage(userBaseInfo.getAreaCode(), phone, 1, 1, "resetLoginPassword", CollectionUtils.buildMap("code", captcha), true);
				mobileMessService.sendMessage(phone, "FogetLoginPassword", true, CollectionUtils.buildMap("code", captcha));
				//this.sendMessage(areaCode, phone, 1, 1, "");
				
				tempInfo.put("areaCode", userBaseInfo.getAreaCode());
				tempInfo.put("phone", phone);
				tempInfo.put("captcha", captcha);
				tempInfo.put("phoneMessageSendCount", phoneMessageSendCount + 1 + "");
				tempInfo.put("phoneMessageVerifyCount", "0");
				tempInfo.put("phoneMessageSendTime", System.currentTimeMillis()+"");
				// 保存重置登录密码的临时信息到redis数据库中
				userRedisDao.savePhoneResetTempInfo(tempInfo);
			}else{
				throw new BusinessException("US602", "Phone message delivery exceeds " 
						+ phoneMessageSendLimit + " limit!", null);
			}
			
		}
		
		
		// 【如果账户是邮箱的情况】
		if(userBaseInfo.getAccountType()==1 && userBaseInfo.getEmail() != null){
			String email = userBaseInfo.getEmail();
			Map<String, String> tempInfo = userRedisDao.getEmailResetTempInfo(email);
			// 邮件发送次数限制为5次
			if(null!=tempInfo || tempInfo.isEmpty() || Integer.parseInt(tempInfo.get("emailMessageSendCount")+"") < emailMessageSendLimit){
				int emailMessageSendCount = 0;
				// 邮箱注册的临时信息存在
				if(null != tempInfo && !tempInfo.isEmpty()){
					emailMessageSendCount = Integer.parseInt(tempInfo.get("emailMessageSendCount") + "");
				}else{
					tempInfo = new HashMap<String,String>();
				}
				
				
				// 生成六位随机数的验证码
				String captcha = CommonUtils.randCode("", 6);
				Map<String, Object> accessData = CollectionUtils.buildMap("email",email,"activeCode",captcha,"toEmail",email,"ctx",ctx);
				// 发送邮箱验证码
				//registerService.sendEmail(email, "resetLoginPassword", 1, accessData, true);
				emailSendService.sendMessage(email, "resetLoginPassword", true, accessData);
				tempInfo = CollectionUtils.buildMap("email",email,"captcha",captcha,"emailMessageSendCount",emailMessageSendCount+1+"","emailMessageVerifyCount","0","emailMessageSendTime",System.currentTimeMillis()+"");
				// 在Redis中保存邮件注册的临时信息
				userRedisDao.saveEmailResetTempInfo(tempInfo);
			}else{
				throw new BusinessException("US619", "Email message delivery exceeds " 
						+ emailMessageSendLimit + " limit!", null);
			}
		}
		return userBaseInfo;
	}


	@Override
	public void lockUser(int userId, byte lockStatus, Date lockDeadline) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void unlockUser(int userId) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @function 判断登录认证的方式
	 * @param userId
	 * @return
	 */
	private int chooseLoginAuthentication(int userId) {
		UserSafeInfo userSafeInfo = userSafeInfoDao.getUserSafeInfoById(userId);
		UserBaseInfo userBaseInfo = userBaseInfoDao.getUserBaseInfoById(userId);
		
		// 1.没有谷歌，没有手机 不做验证；2.有谷歌有手机 验证谷歌；3.有手机没谷歌 验证手机；4.没手机有谷歌 验证谷歌
		int securityLevel = userSafeInfo.getSecurityLevel();
		if(securityLevel==2 || securityLevel==3 || (securityLevel==0 && !StringTools.isBlank(userSafeInfo.getGooglePrivateKey()))){
			// 此时做谷歌验证
			return 2;
		}else if(securityLevel == 0 && StringTools.isBlank(userSafeInfo.getGooglePrivateKey()) && StringTools.isBlank(userBaseInfo.getPhone())){
			// 此时不做验证
			return 0;
		}else{
			// 此时做手机验证
			return 1;
		}
	}

	/**
	 * 根据用户Id获取用户基本信息
	 */
	@Override
	public UserBaseInfo getUserBaseInfo(int userId) {
		UserBaseInfo userBaseInfo = userBaseInfoDao.getUserBaseInfoById(userId);
		if(userBaseInfo == null){
			return null;
		}
		// 防止密码泄露
		userBaseInfo.setPassword("*********");
		return userBaseInfo;
	}

	/**
	 * 获取用户安全信息
	 */
	@Override
	public Map<String, Object> getUserSafeInfo(int userId) {
		UserSafeInfo userSafeInfo = userSafeInfoDao.getUserSafeInfoById(userId);
		if(userSafeInfo == null){
			return null;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		// Bean——>Map
		CollectionUtils.bean2map(map, userSafeInfo);
		map.remove("class");
		map.remove("fundPassword");
		map.remove("googlePrivateKey");
		if(StringTools.isBlank(userSafeInfo.getFundPassword())){
			map.put("hasFundPassword", false);
		}else{
			map.put("hasFundPassword", true);
		}
		if(StringTools.isBlank(userSafeInfo.getGooglePrivateKey())){
			map.put("hasGooglePrivateKey", false);
		}else{
			map.put("hasGooglePrivateKey", true);
		}
		return map;
	}

	/**
	 * 根据用户Id获取用户活动信息
	 */
	@Override
	public UserActivityInfo getUserActivityInfo(int userId) {
		UserActivityInfo userActivityInfo = userActivityInfoDao.getUserActivityInfoById(userId);
		if(userActivityInfo == null){
			return null;
		}
		return userActivityInfo;
	}

	/**
	 * 设置登录认证
	 * @throws BusinessException 
	 */
	@Override
	public void setLoginAuthentication(Integer userId, int loginAuthentication) throws BusinessException {
		UserSafeInfo userSafeInfo = userSafeInfoDao.getUserSafeInfoById(userId);
		// 判断用户是否存在
		if(null == userSafeInfo){
			throw new BusinessException("US753", "The user is not exist!", null);
		}
		
		int loginAuthentication0 = userSafeInfo.getLoginAuthentication();
		// 判断登录认证是否改变
		if(loginAuthentication0 == loginAuthentication){
			throw new BusinessException("US775", "The loginAuthentication has not changed!", null);
		}
		
		/*
		 * loginAuthentication登录认证：0未设置，1设置
		 */
		if(loginAuthentication == 1){
			if(userSafeInfo.getBindPhone()==0 && StringTools.isBlank(userSafeInfo.getGooglePrivateKey())){
				throw new BusinessException("US706", "No securityLevel set! ", null);
			}
		}
		
		userSafeInfo.setLoginAuthentication((byte)loginAuthentication);
		// 更新用户安全信息
		userSafeInfoDao.updateUserSafeInfo(userSafeInfo);
	}

	/**
	 * 校验登录认证时发送手机验证码
	 * @throws BusinessException 
	 */
	@Override
	public void checkLoginAuthenticationSendMessage(Integer userId) throws BusinessException {
		UserSafeInfo userSafeInfo = userSafeInfoDao.getUserSafeInfoById(userId);
		UserBaseInfo userBaseInfo = userBaseInfoDao.getUserBaseInfoById(userId);
		// 判断用户是否存在
		if(null == userSafeInfo){
			throw new BusinessException("US753", "The user is not exist!", null);
		}
		
		// 判断是否绑定了手机
		if(userSafeInfo.getLoginAuthentication() == 0 || userSafeInfo.getLoginAuthentication() == 2){
			throw new BusinessException("US654", "No bind phone", null);
		}
		
		// 获取校验登录认证的临时信息
		Map<String, String> tempInfo = userRedisDao.getCheckLoginAuthenticationTempInfo(userId);
		long nowtime = System.currentTimeMillis(); // 当前时间
		int phoneMessageSendCount =  0;                // 每小时计数
		
		if(tempInfo != null && !tempInfo.isEmpty()){
			long lasttime = Long.parseLong(tempInfo.get("phoneMessageSendTime"));
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
			if(sdf.format(new Date(lasttime)).equals(sdf.format(new Date(nowtime)))){
				phoneMessageSendCount = Integer.parseInt(tempInfo.get("phoneMessageSendCount"));
			}
			if(phoneMessageSendCount >= 5){
				throw new BusinessException("US602", "Phone message delivery exceeds" + phoneSendLimit + "limit!", null);
			}
			
			if(nowtime - lasttime < 1000L*35){
				long last = (1000L*35 - (nowtime-lasttime))/1000L;
				throw new BusinessException("US603", last+"", null);
			}
		}
		String captcha = CommonUtils.randCode("", 6);
		tempInfo = new HashMap<String, String>();
		tempInfo.put("phone", userBaseInfo.getPhone());
		tempInfo.put("captcha", captcha);
		tempInfo.put("phoneMessageSendCount", phoneMessageSendCount + 1 + "");
		tempInfo.put("phoneMessageVerifyCount", 0 + "");
		tempInfo.put("phoneMessageSendTime", nowtime + "");
		
		// 保存验证登录认证的临时信息   
		userRedisDao.saveCheckLoginAuthenticationTempInfo(userId, tempInfo);
		// 调用接口发送短信数据
		//registerService.sendMessage(userBaseInfo.getAreaCode(), userBaseInfo.getPhone(), 1, 1, "loginAuthentication", CollectionUtils.buildMap("code", captcha), true);
		mobileMessService.sendMessage(userBaseInfo.getPhone(), "loginAuthentication", true, CollectionUtils.buildMap("code", captcha));
	}
	
	/**
	 * 校验登录认证
	 */
	@Override
	public void checkLoginAuthentication(Integer userId, String captcha, String pageType) throws BusinessException{
		UserBaseInfo userBaseInfo = userBaseInfoDao.getUserBaseInfoById(userId);
		UserSafeInfo userSafeInfo = userSafeInfoDao.getUserSafeInfoById(userId);
		// 判断用户是否存在
		if(null == userBaseInfo){
			throw new BusinessException("US753", "The user is not exist!", null);
		}
		
		String verifyType = pageType.toString();
		// 登录认证0：未设置
		if("0".equals(verifyType)){
			// 直接放行通过
		}
		// 登录认证1：设置
		if("1".equals(verifyType)){
			/*int chooseLoginAuthentication = this.chooseLoginAuthentication(userId);
			// chooseloginAuthentication: 【0未设置】
			if(chooseLoginAuthentication == 0){
				throw new ParamInvalidException("securityLevel", "There is no such situation!");
			}
			// chooseloginAuthentication: 【1手机验证】
			if(chooseLoginAuthentication == 1){*/
				// 验证手机验证码
				Map<String, String> tempInfo = userRedisDao.getCheckLoginAuthenticationTempInfo(userId);
				// 判断查看校验登录认证的临时信息是否存在
				if(null == tempInfo || tempInfo.isEmpty()){
					throw new BusinessException("US777", "CheckLoginAuthentication is not exist!", null);
				}
				
				// 判断手机验证phoneVerifyLimit手机验证码校验次数限制5次
				int phoneMessageVerifyCount = Integer.parseInt(tempInfo.get("phoneMessageVerifyCount"));
				if(phoneMessageVerifyCount >= 5){
					throw new BusinessException("US603", "Captcha verify exceeds 5 limit", null);
				}
				
				// 验证码超过验证时效
				long phoneMessageSendTime = Long.parseLong(tempInfo.get("phoneMessageSendTime"));
				   // 获取验证码时效
				long codeValidTime = RedisKeyUtils.getCaptchaValidTime();
				long currentTime = System.currentTimeMillis();
				   // 判断手机验证码是否失效
				if(currentTime - phoneMessageSendTime > codeValidTime*1000){
					throw new BusinessException("US604", "Captcha is invalid", null);
				}
				
				// 验证码错误
				String captchaTemp = tempInfo.get("captcha");
				if(!captcha.equals(captchaTemp)){
					String key = RedisKeyUtils.getCheckLoginAuthenticationTempInfoKey(userId);
					// 手机验证码校验次数+1
					userRedisDao.incVerifyCount(key);
					throw new BusinessException("US605", "Captcha is error", null);
				}
				
				// 手机验证通过删除校验登录认证的临时信息
				userRedisDao.removeCheckLoginAuthentication(userId);
			}
	     
			// chooseloginAuthentication：【2 谷歌认证】
			if("2".equals(verifyType)){
				// 没有绑定谷歌私钥提示错误
				if(StringTools.isBlank(userSafeInfo.getGooglePrivateKey())){
					throw new BusinessException("US802", "No bind googlePrivateKey", null);
				}else{
					// 谷歌验证且有谷歌私钥则进行验证
					String googlePrivateKey = userSafeInfo.getGooglePrivateKey();
					// 调用谷歌认证接口进行验证
					boolean isAuth = GoogleAuthUtils.authcode(captcha, googlePrivateKey);
					if(!isAuth){
						throw new BusinessException("US606", "GoogleCaptcha is error!", null);
					}
				}
			}
		
	}

	/**
	 * 登录时忘记登录密码更改密码的方法
	 * @throws BusinessException 
	 */
	@SuppressWarnings("unused")
	@Override
	public void changeLoginPassword(Integer userId, String captcha, String password, Map<String,String> map) throws BusinessException {
		// 判断map选择从redis中取什么信息
		String areaCode = map.get("areaCode");
		String phone = map.get("phone");
		String email = map.get("email");
		if(null != email && !email.isEmpty()){
			// 用户账号为邮箱
			
			Map<String, String> tempInfo = userRedisDao.getEmailResetTempInfo(email);
			if(null == tempInfo){
				throw new BusinessException("US657","No account needs to be reset!", null);
			}
						
			Integer emailMessageVerifyCount = Integer.parseInt(tempInfo.get("emailMessageVerifyCount"));
			// phoneMessageVerifyLimit手机验证码验证次数限制5次
			if(emailMessageVerifyCount >= emailMessageVerifyLimit){
				throw new BusinessException("US603", "Captcha verify exceeds" + emailMessageVerifyLimit + "limit!", null);
			}
						
			String captchaTemp = tempInfo.get("captcha");
			long sendTime = Long.parseLong(tempInfo.get("emailMessageSendTime"));
			long currentTime = System.currentTimeMillis();
			// 手机验证码失效时间10分钟
			long captchaValidTime = RedisKeyUtils.getCaptchaValidTime();
			// 判断手机验证码是否失效
			if(currentTime - sendTime > captchaValidTime*1000){
				throw new BusinessException("US604", "Captcha is invalid!", null);
			}
			// 校验验证码
			if(!captcha.equals(captchaTemp)){
			String tempInfoKey = RedisKeyUtils.getEmailResetTempInfoKey(email);
			// 验证码验证次数增加
			userRedisDao.addVerifyCount(tempInfoKey);
			   throw new BusinessException("US605", "Captcha is error!", null);
			}
			// 删除手机注册的临时信息
			userRedisDao.removeEmailResetTempInfo(email);
		}
		if(null != areaCode && !areaCode.isEmpty() && null != phone && !phone.isEmpty()){
			// 用户账户为手机
			Map<String, String> tempInfo = userRedisDao.getPhoneResetTempInfo(phone);
			if(null == tempInfo){
				throw new BusinessException("US657","No account needs to be reset!", null);
			}
			
			Integer phoneMessageVerifyCount = Integer.parseInt(tempInfo.get("phoneMessageVerifyCount"));
			// phoneMessageVerifyLimit手机验证码验证次数限制5次
			if(phoneMessageVerifyCount >= phoneMessageVerifyLimit){
				throw new BusinessException("US603", "Captcha verify exceeds" + phoneMessageVerifyLimit + "limit!", null);
			}
			
			String captchaTemp = tempInfo.get("captcha");
			long sendTime = Long.parseLong(tempInfo.get("phoneMessageSendTime"));
			long currentTime = System.currentTimeMillis();
			// 手机验证码失效时间10分钟
			long captchaValidTime = RedisKeyUtils.getCaptchaValidTime();
			// 判断手机验证码是否失效
			if(currentTime - sendTime > captchaValidTime*1000){
				throw new BusinessException("US604", "Captcha is invalid!", null);
			}
			// 校验验证码
			if(!captcha.equals(captchaTemp)){
				String tempInfoKey = RedisKeyUtils.getPhoneResetTempInfoKey(phone);
				// 验证码验证次数增加
				userRedisDao.addVerifyCount(tempInfoKey);
				throw new BusinessException("US605", "Captcha is error!", null);
			}
			// 删除手机注册的临时信息
			userRedisDao.removePhoneResetTempInfo(phone);
		}
		
			int length = password.length();
			// 密码安全等级
			byte passwordLevel = 0;
			if(length <= 12){
				passwordLevel = 1;
			}else if(length <= 16){
				passwordLevel = 2;
			}else{
				passwordLevel = 3;
			}
			// 对密码进行MD5加密
			password = CommonUtils.EncoderByMd5(password);
			UserBaseInfo userBaseInfo = new UserBaseInfo();
			userBaseInfo.setUserId(userId);
			userBaseInfo.setPassword(password);
			
			userBaseInfoDao.updateUserBaseInfoByUserId(userBaseInfo);
	}
	
	
}
